/**
 * 
 */   
package com.cares.infobird.web;  

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JRElement;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JRDesignBand;
import net.sf.jasperreports.engine.design.JRDesignElement;
import net.sf.jasperreports.engine.design.JRDesignSection;
import net.sf.jasperreports.engine.design.JRDesignTextField;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cares.core.base.controller.BaseController;
import com.cares.core.base.exception.ApplyException;
import com.cares.core.common.service.DicService;
import com.cares.core.common.service.RegionService;
import com.cares.core.mng.service.AccountService;
import com.cares.core.utils.Constant;
import com.cares.core.utils.StringUtil;
import com.cares.core.utils.SystemConfiguration;
import com.cares.core.utils.oConvertUtils;
import com.cares.core.utils.time.JodaTime;
import com.cares.entity.base.DataGridModel;
import com.cares.entity.base.PageModel;
import com.cares.entity.common.Dic;
import com.cares.entity.common.Region;
import com.cares.entity.infobird.CallBusi;
import com.cares.entity.infobird.CallOrder;
import com.cares.entity.infobird.CallRecord;
import com.cares.entity.infobird.CustomerInfo;
import com.cares.entity.infobird.Location;
import com.cares.entity.infobird.NoticeInfo;
import com.cares.entity.mng.User;
import com.cares.infobird.service.CallOrderService;
import com.cares.infobird.service.CallRecordService;
import com.cares.infobird.service.CustomerInfoService;
import com.cares.infobird.service.LocationService;
import com.cares.infobird.service.NoticeInfoService;
import com.cares.infobird.util.NumberUtil;

/**   
 * @作者 Stone
 * @创建日期 2014-7-26 下午12:20:43
 * @版本 V1.0
 * @类说明
 */
@Controller
@RequestMapping(value="/infobird/call")
public class CallRecordController extends BaseController {
	
	@Resource(name="callRecordService")
	private CallRecordService callRecordService;
	
	@Resource(name="callOrderService")
	private CallOrderService callOrderService;
	
	@Resource(name="customerInfoService")
	private CustomerInfoService customerInfoService;
	
	@Resource(name="noticeInfoService")
	private NoticeInfoService noticeInfoService;
	
	@Resource(name="accountService")
	protected AccountService accountService;
	
	@Resource(name="regionService")
	protected RegionService regionService;
	
	@Resource(name="dicService")
	protected DicService dicService;
	
	@Resource(name="locationService")
	private LocationService locationService;
	
	/**
	 * GET方法，用户列表页面加载
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String init(HttpServletRequest request) {
		//获取弹屏标识
		List<Dic> actionTypeList = callRecordService.getDicList4Combobox("actionType", "query");
		request.setAttribute("actionTypeList", actionTypeList);
		//获取呼叫类型
		List<Dic> callTypeList = callRecordService.getDicList4Combobox("callType", "query");
		request.setAttribute("callTypeList", callTypeList);
		return "infobird/call/callList";
	}
	
	/**
	 * GET方法，用户列表页面加载
	 */
	@RequestMapping(value="/order", method = RequestMethod.GET)
	public String initOrderListWin(HttpServletRequest request) {
		//获取工单类型
		List<Dic> typeList = callRecordService.getDicList4Combobox("order_type", "query");
		request.setAttribute("typeList", typeList);
		//获取处理类型
		request.setAttribute("dealFlagList", Constant.LOGIC_TYPE);
		
		request.setAttribute("agentName", callRecordService.getCurrentUserNm());
		return "infobird/call/orderList";
	}
	
	/**
	 * GET方法，业务接触列表页面加载
	 */
	@RequestMapping(value="/busi", method = RequestMethod.GET)
	public String initBusiListWin(HttpServletRequest request) {
		//获取工单类型
		List<Dic> typeList = callRecordService.getDicList4Combobox("order_type", "query");
		request.setAttribute("typeList", typeList);
		//获取一级业务分类
		List<Dic> voiceList = callOrderService.getParentBusiness("voiceBusiness");
		request.setAttribute("voiceList", voiceList);
		//获取处理类型
		request.setAttribute("dealFlagList", Constant.LOGIC_TYPE);
		
		request.setAttribute("agentName", callRecordService.getCurrentUserNm());
		return "infobird/call/busiList";
	}
	
	@RequestMapping(value="/addWin2", method=RequestMethod.GET)
	public String addWin2(HttpServletRequest request, HttpServletResponse response) {
		//初始化Model
		CallRecord record = new CallRecord();
		
		String phoneNo = "";
		
		//获取呼入参数
		String actionType = oConvertUtils.getString(request.getParameter("actiontype"));
		
		String corpName = oConvertUtils.getString(request.getParameter("corpname"));
		
		String deptName = oConvertUtils.getString(request.getParameter("deptname"));
		
		String agentName = oConvertUtils.getString(request.getParameter("agentname"));
		
		String callId = oConvertUtils.getString(request.getParameter("callid"));
		
		String callerId = oConvertUtils.getString(request.getParameter("callerid"));
		
		String calleeId = oConvertUtils.getString(request.getParameter("calleeid"));
		
		String callType = oConvertUtils.getString(request.getParameter("calltype"));
		
		String uuId = oConvertUtils.getString(request.getParameter("uuid"));
		
		String originalData = oConvertUtils.getString(request.getParameter("OriginalData"));
		
		//字符编码转换
		try {
			StringBuilder sb = new StringBuilder();
			sb.append(new String(corpName.getBytes("UTF-8"),"GBK")).append("|");
			sb.append(new String(corpName.getBytes("GBK"),"UTF-8")).append("|");
			sb.append(new String(corpName.getBytes("UTF-8"),"GB2312")).append("|");
			sb.append(new String(corpName.getBytes("GB2312"),"UTF-8")).append("|");
			sb.append(new String(corpName.getBytes("UTF-8"),"ISO8859-1")).append("|");
			sb.append(new String(corpName.getBytes("ISO8859-1"),"UTF-8")).append("|");
			record.setRemark(sb.toString());
			logger.error("==================================");
			
			
			
			//logger.error("GB2312 - UTF-8 =="+new String(corpName.getBytes("GB2312"),"UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(!"StartService".equals(actionType)) {
			if("CallPhone".equals(actionType)) {
				phoneNo = callerId;
			} else if("OutDial".equals(actionType)) {
				phoneNo = calleeId;
			}
			
			record.setActionType(actionType);
			record.setCorpName(corpName);
			record.setDeptName(deptName);
			record.setAgentName(agentName);
			record.setCallId(callId);
			record.setCallerId(callerId);
			record.setCalleeId(calleeId);
			record.setCallNo(phoneNo);
			record.setCallType(Integer.parseInt(callType));
			record.setUuId(uuId);
			record.setOriginalData(originalData);
			
			//获取工单编号
			record.setOrderNo(callRecordService.updateOrderNo());
			
			//获取呼叫记录信息
			record.setCreateUser(getAgentName(request));
			record = callRecordService.saveRecord(record);
			
			request.setAttribute("record", record);
			
			CustomerInfo cust = null;
			//去除区号中的横线
			phoneNo = phoneNo.replaceAll("-", "");
			
			//判断号码类型
			NumberUtil.Number num = NumberUtil.checkNumber(phoneNo);
			if(NumberUtil.PhoneType.CELLPHONE.equals(num.getType())) {
				//根据手机号码查询客户信息
				cust = customerInfoService.getByMobile(phoneNo);	
			} else if(NumberUtil.PhoneType.FIXEDPHONE.equals(num.getType())) {
				//根据固定号码查询客户信息
				cust = customerInfoService.getByPhoneNo(phoneNo);
			}
			
			if(cust!=null) {
				request.setAttribute("custFlag", "Y");
			} else {
				request.setAttribute("custFlag", "N");
				cust = new CustomerInfo();
				if(NumberUtil.PhoneType.CELLPHONE.equals(num.getType())) {
					cust.setMobile(phoneNo);
					Location location = locationService.find(phoneNo);
					cust.setProvince(location.getProvince());
					cust.setCity(location.getCity());
					if(StringUtil.isNotEmpty(cust.getProvince())) {
						cust.setDependency(location.getProvince() + "-" + location.getCity());
					} else {
						cust.setProvince("其他");
						cust.setDependency("其他");
					}
				} else if(NumberUtil.PhoneType.FIXEDPHONE.equals(num.getType())) {
					cust.setTelephone(phoneNo);
					
					//根据区划查询归属地信息
					if(StringUtils.isNotEmpty(num.getCode())) {
						cust.setTelAbbr(num.getCode());
						Region region = regionService.getByAreaCode(num.getCode());
						if(region.getRegionType()==1) {
							//直辖市
							cust.setProvince(region.getShortName());
							cust.setCity(region.getShortName());
							cust.setDependency(region.getShortName() + "-" + region.getShortName());
						} else {
							//非直辖市
							cust.setProvince(region.getParentShortName());
							cust.setCity(region.getShortName());
							cust.setDependency(region.getParentShortName() + "-" + region.getShortName());
						}
					} else {
						cust.setProvince("其他");
						cust.setDependency("其他");
					}
				} else {
					//未知类型
					cust.setTelephone(phoneNo);
					cust.setProvince("其他");
					cust.setDependency("其他");
				}
				
			}
			request.setAttribute("cust", cust);
			
			//获取证件类型
			List<Dic> dicList = callRecordService.getDicList4Combobox("certType", "query");
			request.setAttribute("dicList", dicList);
			
			List<Dic> voiceBusiList = dicService.getFirstBusiness("voiceBusiness");
			request.setAttribute("voiceBusiList", voiceBusiList);
			
			request.setAttribute("agentName", agentName);
			HttpSession session = request.getSession();
			String sessionAgent = (String)session.getAttribute("agentName");
			if(StringUtils.isEmpty(sessionAgent)){
				session.setAttribute("agentName", agentName);
			}
			
			return "infobird/call/callAdd2";
		} else {
			String logoninfo = oConvertUtils.getString(request.getParameter("logoninfo"));
			String logoninfocoded = oConvertUtils.getString(request.getParameter("logoninfocoded"));
			String loginsign = oConvertUtils.getString(request.getParameter("loginsign"));
			String enterprise_name = oConvertUtils.getString(request.getParameter("enterprise_name"));
			String username = oConvertUtils.getString(request.getParameter("username"));
			
			StringBuilder sb = new StringBuilder();
			sb.append("infobird");
			sb.append("|").append(agentName);
			sb.append("|").append(corpName);
			sb.append("|").append(deptName);
			sb.append("|").append(logoninfo);
			sb.append("|").append(logoninfocoded);
			sb.append("|").append(enterprise_name);
			sb.append("|").append(username);
			
			User user = accountService.findUserByLoginName("infobird_agent", true);
			
			request.setAttribute("username", user.getLoginName());
			request.setAttribute("password", SystemConfiguration.getPropertyValue("voice.pass"));
			request.setAttribute("source", sb.toString());
			
			HttpSession session = request.getSession();
			session.setAttribute("agentName", agentName);
			return "infobird/call/fakeLogin";
		}
		
		
	}
	
	public static String getEncoding(String str) {      
	       String encode = "GB2312";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s = encode;      
	              return s;      
	           }      
	       } catch (Exception exception) {      
	       }      
	       encode = "ISO-8859-1";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s1 = encode;      
	              return s1;      
	           }      
	       } catch (Exception exception1) {      
	       }      
	       encode = "UTF-8";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s2 = encode;      
	              return s2;      
	           }      
	       } catch (Exception exception2) {      
	       }      
	       encode = "GBK";      
	      try {      
	          if (str.equals(new String(str.getBytes(encode), encode))) {      
	               String s3 = encode;      
	              return s3;      
	           }      
	       } catch (Exception exception3) {      
	       }      
	      return "";      
	   }
	
	@RequestMapping(value="/viewHis", method=RequestMethod.GET)
	public String viewHistory(HttpServletRequest request) {
		String id = oConvertUtils.getString(request.getParameter("id"));
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		CallOrder order = null;
		CustomerInfo cust = null;
		if (StringUtil.isNotEmpty(id)) {
			order = callOrderService.get(Long.parseLong(id));
		}
		
		if(order!=null && order.getCustId()!=null) {
			//根据客户ID获取客户信息
			cust = customerInfoService.get(order.getCustId());
		}
		//获取证件类型
		List<Dic> dicList = callRecordService.getDicList4Combobox("certType", "query");
		request.setAttribute("dicList", dicList);
		request.setAttribute("order", order);
		request.setAttribute("cust", cust);
		request.setAttribute("opt", opt);
		return "infobird/call/orderHistory";
	}
	
	@RequestMapping(value="/addWin", method=RequestMethod.GET)
	public String addWin(HttpServletRequest request) {
		CallOrder order = null;
		CustomerInfo cust = null;
		
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		request.setAttribute("opt", opt);
		
		if("DEAL".equals(opt) || "VIEW".equals(opt)) {
			String orderId = oConvertUtils.getString(request.getParameter("orderId"));
			if (StringUtil.isNotEmpty(orderId)) {
				order = callOrderService.get(Long.parseLong(orderId));
				if(order!=null && order.getParentBusinessId()!=null) {
					request.setAttribute("sonBusinessList", dicService.getLeavesBusiness(order.getParentBusinessId().longValue()));
				}
			}
			
			if(order!=null && order.getCustId()!=null) {
				//根据客户ID获取客户信息
				cust = customerInfoService.get(order.getCustId());
			}
		}
		
		//获取证件类型
		List<Dic> dicList = callRecordService.getDicList4Combobox("certType", "query");
		request.setAttribute("dicList", dicList);
		
		request.setAttribute("settleList", callOrderService.getParentBusiness("settleBusiness"));
		request.setAttribute("order", order);
		request.setAttribute("cust", cust);
		
		return "infobird/call/callAdd";
	}
	
	@RequestMapping(value="/dealWin", method=RequestMethod.GET)
	public String dealWin(HttpServletRequest request) {
		String id = oConvertUtils.getString(request.getParameter("id"));
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		CallOrder order = null;
		CustomerInfo cust = null;
		if (StringUtil.isNotEmpty(id)) {
			order = callOrderService.get(Long.parseLong(id));
		}
		
		if(order!=null && order.getCustId()!=null) {
			//根据客户ID获取客户信息
			cust = customerInfoService.get(order.getCustId());
		}
		
		//获取证件类型
		List<Dic> dicList = callRecordService.getDicList4Combobox("certType", "query");
		request.setAttribute("dicList", dicList);
		
		request.setAttribute("opt", opt);
		request.setAttribute("order", order);
		request.setAttribute("cust", cust);
		return "infobird/call/orderDeal";
	}
	
	@RequestMapping(value="/list", method=RequestMethod.POST)
	public void getDateGrid(DataGridModel dgm, CallRecord record, HttpServletResponse response) {
		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		PageModel<CallRecord> pageModel = new PageModel<CallRecord>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(record);
		String result = callRecordService.list(pageModel);
		System.out.println(result);
		try {
			this.renderText(response, result);
		} catch (IOException e) {
			
		}
		
	}
	
	@RequestMapping(value="/del", method=RequestMethod.GET)
	public @ResponseBody Map<String, String> delete(@RequestParam("id") List<String> ids) {
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			this.callRecordService.delete(ids);
			map.put(AJAX_MESSAGE, "true");
		} catch(NumberFormatException e) {
			map.put(AJAX_MESSAGE, "false");
		} catch (ApplyException e) {
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}
	
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> addFlight(@RequestBody CallRecord record, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>(1);
		
		String opt = oConvertUtils.getString(request.getParameter("opt"));
		
		try {
			if("N".equals(opt)){
				record.setCreateUser(getAgentName(request));
				this.callRecordService.save(record);
			} else if("E".equals(opt)){
				record.setUpdateUser(getAgentName(request));
				this.callRecordService.update(record);
			}
			map.put(AJAX_MESSAGE, "true");
		} catch (ApplyException e) {
			map.put(AJAX_MESSAGE, "false");
		}
		return map;
	}
	
	@RequestMapping(value="/orderlist", method=RequestMethod.POST)
	public void getOrderGrid(DataGridModel dgm, CallOrder model, HttpServletResponse response) {
		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		PageModel<CallOrder> pageModel = new PageModel<CallOrder>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(model);
		String result = callOrderService.list(pageModel);
		System.out.println(result);
		try {
			this.renderText(response, result);
		} catch (IOException e) {
			
		}
		
	}
	
	@RequestMapping(value="/busilist", method=RequestMethod.POST)
	public void getOrderGrid(DataGridModel dgm, CallBusi model, HttpServletResponse response) {
		int pageNo = dgm.getPage();
		int pageSize = dgm.getRows();
		String order = dgm.getOrder();
		String sort = dgm.getSort();
		PageModel<CallBusi> pageModel = new PageModel<CallBusi>(pageNo, pageSize);
		pageModel.setOrder(order);
		pageModel.setSort(sort);
		pageModel.setCondition(model);
		String result = callOrderService.busiList(pageModel);
		System.out.println(result);
		try {
			this.renderText(response, result);
		} catch (IOException e) {
			
		}
		
	}
	
	@RequestMapping(value="/exportBusiList", method=RequestMethod.POST)
	public void exportBusiList(DataGridModel dgm, CallBusi model, HttpServletResponse response) {
		SimpleDateFormat dt = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
		//取得数据集合
		List<CallBusi> result = null;
		String fileName = "工单列表"+dt.format(dateProvider.getDate()) +".xls";
		try {
			//获取数据
			PageModel<CallBusi> pageModel = new PageModel<CallBusi>(1, 65000);
			pageModel.setCondition(model);
			result = callOrderService.getBusiList(pageModel);
			
			JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(result);
			/* 
             * 设置头信息 
             */
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
			
			//动态模板编辑
			String rootReportDir = this.getClass().getResource("/").getPath().replaceAll("%20", " ");
			String designFileName = rootReportDir + File.separator + "reportTemplet"+ File.separator +"busi_list.jrxml";
			JasperDesign jDesign = JRXmlLoader.load(designFileName);
			
			String[] dynamicKeyCol = new String[]{"orderNo", 
					"businessFlow", "remark", "acctNo", "createUser",
					"createTime", "dealUser", "dealTime", "dealFlag"};
			JasperDesign dynamicJDesign = this.getDynamicJasperDesign(jDesign, Arrays.asList(dynamicKeyCol));
			
			Map<String, Object> params = new HashMap<String, Object>(); 
			JasperReport jasperReport = JasperCompileManager.compileReport(jDesign);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, ds);
			
			//出力
			JRXlsExporter exporter = new JRXlsExporter();
			OutputStream  ouputStream = response.getOutputStream();
			exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, ouputStream);
			exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,Boolean.TRUE);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN,Boolean.FALSE);
			exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);
			exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.FALSE);
			exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);
			exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES,new String[]{"Sheet1"});
			exporter.exportReport();
			ouputStream.flush();
			ouputStream.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private JasperDesign getDynamicJasperDesign(JasperDesign jdesign, Collection<String> dynamicCol) { 
		JRDesignBand headerBand = (JRDesignBand)jdesign.getColumnHeader();
		JRDesignSection section = (JRDesignSection)jdesign.getDetailSection();
		JRDesignBand detailBand = (JRDesignBand) section.getBands()[0];
				
		JRElement[] hElements = headerBand.getElements();
		JRElement[] dElements = detailBand.getElements();
		
		int currentX = 0;
		for(int i=0; i<dElements.length; i++){
			JRDesignElement element = (JRDesignElement) dElements[i];
			String key = element.getKey();
			JRDesignElement headElement = (JRDesignElement) hElements[i];
			
			if(element!=null && element instanceof JRDesignTextField){
				if(!dynamicCol.contains(key)){
					detailBand.removeElement(element);
					headerBand.removeElement(headElement);
				}else{
					element.setX(currentX);
					headElement.setX(currentX);
					currentX += element.getWidth();
				}
			}
		}
		JRDesignBand titleBand = (JRDesignBand)jdesign.getTitle();
		JRElement tElements = titleBand.getElementByKey("title");
		tElements.setWidth(currentX);
		return jdesign;
	}
	
	@RequestMapping(value="/saveOrder", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> saveOrder(HttpServletRequest request, @RequestBody Map<String, Object> parmMap) {
		Map<String, String> map = new HashMap<String, String>(1);
		CustomerInfo cust = new CustomerInfo();
		CallOrder model = new CallOrder();
		CustomerInfo dbCust = null;
		Long custId = null;
		if(StringUtils.isNotEmpty((String)parmMap.get("custId"))) {
			//客户信息不为空
			custId = Long.parseLong((String)parmMap.get("custId"));
			dbCust = customerInfoService.get(custId);
			if(dbCust!=null && dbCust.getId()>0) {
				cust.setId(custId);
				cust.setMobile(dbCust.getMobile());
				cust.setTelephone(dbCust.getTelephone());
			} else {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "客户信息异常");
				return map;
			}
		}
		String custType = (String) parmMap.get("custType");
		cust.setCustType(Integer.parseInt(custType));
		cust.setName((String) parmMap.get("name"));
		cust.setSex((String) parmMap.get("sex"));
		if(custId==null) {
			//新增客户时才可修改手机
			cust.setMobile((String) parmMap.get("mobile"));
		}
		cust.setAcctNo((String) parmMap.get("acctNo"));
		cust.setCertType((String) parmMap.get("certType"));
		cust.setCertNo((String) parmMap.get("certNo"));
		String birthDay = (String) parmMap.get("birth");
		cust.setBirth(JodaTime.toDate(birthDay));
		if(custId==null) {
			//新增客户时才可修改固话
			String tel = (String) parmMap.get("telephone");
			//去除固话中的特殊字符
			tel = tel.replaceAll("[（），、\\-\\(\\)\\,\\\\]",""); 
			cust.setTelephone(tel);
		}
		cust.setFax((String) parmMap.get("fax"));
		if(custId==null) {
			//新增客户时才可修改归属地信息
			cust.setDependency((String) parmMap.get("dependency"));
			cust.setProvince((String) parmMap.get("province"));
			cust.setCity((String) parmMap.get("city"));
		}
		cust.setEmail((String) parmMap.get("email"));
		cust.setAddress((String) parmMap.get("address"));
		cust.setZipCode((String) parmMap.get("zipCode"));
		
		if(custId!=null && custId>0) {
			//更新客户信息
			cust.setUpdateUser(getAgentName(request));
			customerInfoService.update(cust);
		} else {
			//新增客户信息
			
			if(StringUtils.isNotEmpty(cust.getMobile())) {
				//根据手机号码判断客户是否存在
				CustomerInfo dbCust1 = customerInfoService.getByMobile(cust.getMobile());
				
				if(dbCust1!=null && dbCust1.getId()>0) {
					map.put(AJAX_MESSAGE, "false");
					map.put(ERR_MESSAGE, "该手机号码已存在");
					return map;
				}
			}
			
			if(StringUtils.isNotEmpty(cust.getTelephone())) {
				//根据固定号码判断客户是否存在
				CustomerInfo dbCust2 = customerInfoService.getByPhoneNo(cust.getTelephone());
				if(dbCust2!=null && dbCust2.getId()>0) {
					map.put(AJAX_MESSAGE, "false");
					map.put(ERR_MESSAGE, "该固定电话已存在");
					return map;
				}
			}
			
			//新增客户信息
			cust.setCreateUser(getAgentName(request));
			customerInfoService.save(cust);
			custId = cust.getId();
		}
		String orderId = (String) parmMap.get("orderId");
		if(StringUtils.isNotEmpty(orderId)) {
			model.setId(Long.parseLong(orderId));
		}
		model.setOrderNo((String) parmMap.get("orderNo"));
		String recordId = (String)parmMap.get("recordId");
		if(StringUtils.isNotEmpty(recordId)) {
			model.setRecordId(Long.parseLong(recordId));
		}
		model.setCustId(custId);
		Integer orderType = Integer.parseInt((String)parmMap.get("orderType"));
		model.setOrderType(orderType);
		String busiId = (String)parmMap.get("businessId");
		if(StringUtils.isNotEmpty(busiId)) {
			model.setBusinessId(Integer.parseInt(busiId));
			model.setParentBusinessId(Integer.parseInt(dicService.getParentBusinessId(Long.parseLong(busiId))));
			model.setParentBusinessFlow(callOrderService.getBusiness(model.getParentBusinessId().longValue()));
			model.setBusinessFlow(callOrderService.getParentBusiness(Long.parseLong(busiId)));
		}
		if(StringUtils.isNotEmpty((String)parmMap.get("dealFlag"))) {
			model.setDealFlag((String) parmMap.get("dealFlag"));
		}
		//暂时不需要工单处理状态字段
		//model.setStatus(0);//工单默认处理状态为处理中
		model.setAcctNo((String) parmMap.get("acctNo"));
		model.setRemark((String) parmMap.get("remark"));
		String agentName = (String) parmMap.get("agentName");//工单录入坐席
		model.setAgentName(agentName);
		
		String smsFlag = (String) parmMap.get("smsFlag");
		String emailFlag = (String) parmMap.get("emailFlag");
		String mobileNo = (String) parmMap.get("mobileNo");
		String emailAdd = (String) parmMap.get("emailAdd");
		String smsContent = (String) parmMap.get("smsContent");
		String emailContent = (String) parmMap.get("emailContent");
		model.setSmsFlag(smsFlag);
		model.setEmailFlag(emailFlag);
		
		//消息推送记录
		NoticeInfo info = null;
		
		try {
			if(model.getId()!=null && model.getId()>0) {
				model.setUpdateUser(getAgentName(request));
				callOrderService.update(model);
			} else {
				if("Y".equals(model.getDealFlag())) {
					model.setDealUser(getAgentName(request));
					model.setDealTime(dateProvider.getDate());
				}
				model.setCreateUser(getAgentName(request));
				callOrderService.save(model);
			}
			
			if("Y".equals(smsFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender("SYS");
				info.setReceiver(mobileNo);
				info.setSubject(null);
				info.setContent(smsContent);
				info.setChannel("MOBILE");
				info.setAddress(mobileNo);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(custId);
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			
			if("Y".equals(emailFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender(SystemConfiguration.getPropertyValue("mail.sender"));
				info.setReceiver(emailAdd);
				if(orderType==1) {
					info.setSubject("话务工单消息通知");
				} else if(orderType==2) {
					info.setSubject("结算工单消息通知");
				}
				info.setContent(emailContent);
				info.setChannel("EMAIL");
				info.setAddress(emailAdd);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(custId);
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			map.put(AJAX_MESSAGE, "true");
			map.put("custId", custId.toString());
			map.put("mobile", cust.getMobile());
			map.put("email", cust.getEmail());
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "话务工单保存异常");
		}
		return map;
	}
	
	@RequestMapping(value="/saveSettle", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> saveSettle(HttpServletRequest request, @RequestBody Map<String, Object> parmMap) {
		Map<String, String> map = new HashMap<String, String>(1);
		CustomerInfo cust = new CustomerInfo();
		CallOrder model = new CallOrder();
		CustomerInfo dbCust = null;
		Long custId = null;
		if(StringUtils.isNotEmpty((String)parmMap.get("custId"))) {
			//客户信息不为空
			custId = Long.parseLong((String)parmMap.get("custId"));
			dbCust = customerInfoService.get(custId);
			if(dbCust!=null && dbCust.getId()>0) {
				cust.setId(custId);
				cust.setMobile(dbCust.getMobile());
				cust.setTelephone(dbCust.getTelephone());
			} else {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "客户信息异常");
				return map;
			}
		}
		String custType = (String) parmMap.get("custType");
		cust.setCustType(Integer.parseInt(custType));
		cust.setName((String) parmMap.get("name"));
		cust.setSex((String) parmMap.get("sex"));
		String mobile = (String) parmMap.get("mobile");
		if(StringUtils.isNotEmpty(mobile)) {
			cust.setMobile(mobile);
		}
		cust.setAcctNo((String) parmMap.get("acctNo"));
		cust.setCertType((String) parmMap.get("certType"));
		cust.setCertNo((String) parmMap.get("certNo"));
		String birthDay = (String) parmMap.get("birth");
		cust.setBirth(JodaTime.toDate(birthDay));
		//新增客户时才可修改固话
		String tel = (String) parmMap.get("telephone");
		//去除固话中的特殊字符
		tel = tel.replaceAll("[（），、\\-\\(\\)\\,\\\\]","");
		if(StringUtils.isNotEmpty(tel)) {
			cust.setTelephone(tel);
		}
		cust.setFax((String) parmMap.get("fax"));
		if(custId==null) {
			//新增客户时才可修改归属地信息
			cust.setDependency((String) parmMap.get("dependency"));
			cust.setProvince((String) parmMap.get("province"));
			cust.setCity((String) parmMap.get("city"));
		}
		cust.setEmail((String) parmMap.get("email"));
		cust.setAddress((String) parmMap.get("address"));
		cust.setZipCode((String) parmMap.get("zipCode"));
		
		if(custId!=null && custId>0) {
			//更新客户信息
			cust.setUpdateUser(getAgentName(request));
			customerInfoService.update(cust);
		} else {
			//新增客户信息
			if(StringUtils.isNotEmpty(cust.getMobile())) {
				//根据手机号码判断客户是否存在
				CustomerInfo dbCust1 = customerInfoService.getByMobile(cust.getMobile());
				
				if(dbCust1!=null && dbCust1.getId()>0) {
					map.put(AJAX_MESSAGE, "false");
					map.put(ERR_MESSAGE, "该手机号码已存在");
					return map;
				}
			}
			
			if(StringUtils.isNotEmpty(cust.getTelephone())) {
				//根据固定号码判断客户是否存在
				CustomerInfo dbCust2 = customerInfoService.getByPhoneNo(cust.getTelephone());
				if(dbCust2!=null && dbCust2.getId()>0) {
					map.put(AJAX_MESSAGE, "false");
					map.put(ERR_MESSAGE, "该固定电话已存在");
					return map;
				}
			}
			
			//新增客户信息
			cust.setCreateUser(getAgentName(request));
			customerInfoService.save(cust);
			custId = cust.getId();
		}
		
		String orderId = (String) parmMap.get("orderId");
		if(StringUtils.isNotEmpty(orderId)) {
			model.setId(Long.parseLong(orderId));
		}
		model.setOrderNo((String) parmMap.get("orderNo"));
		String recordId = (String)parmMap.get("recordId");
		if(StringUtils.isNotEmpty(recordId)) {
			model.setRecordId(Long.parseLong(recordId));
		}
		model.setCustId(custId);
		Integer orderType = Integer.parseInt((String)parmMap.get("orderType"));
		model.setOrderType(orderType);
		String busiId = (String)parmMap.get("businessId");
		if(StringUtils.isNotEmpty(busiId)) {
			model.setBusinessId(Integer.parseInt(busiId));
			model.setBusinessFlow(callOrderService.getParentBusiness(Long.parseLong(busiId)));
		}
		String parentBusiId = (String)parmMap.get("parentBusinessId");
		if(StringUtils.isNotEmpty(parentBusiId)) {
			model.setParentBusinessId(Integer.parseInt(parentBusiId));
			model.setParentBusinessFlow(callOrderService.getBusiness(model.getParentBusinessId().longValue()));
		}
		if(StringUtils.isNotEmpty((String)parmMap.get("dealFlag"))) {
			model.setDealFlag((String) parmMap.get("dealFlag"));
		}
		model.setStatus(0);//工单默认处理状态为处理中
		model.setAcctNo((String) parmMap.get("acctNo"));
		model.setRemark((String) parmMap.get("remark"));
		
		String smsFlag = (String) parmMap.get("smsFlag");
		String emailFlag = (String) parmMap.get("emailFlag");
		String mobileNo = (String) parmMap.get("mobileNo");
		String emailAdd = (String) parmMap.get("emailAdd");
		String smsContent = (String) parmMap.get("smsContent");
		String emailContent = (String) parmMap.get("emailContent");
		model.setSmsFlag(smsFlag);
		model.setEmailFlag(emailFlag);
		
		//消息推送记录
		NoticeInfo info = null;
		
		try {
			if(model.getId()!=null && model.getId()>0) {
				model.setStatus(2);
				model.setDealUser(getAgentName(request));
				model.setDealTime(new Date());
				model.setUpdateUser(getAgentName(request));
				callOrderService.update(model);
			} else {
				model.setOrderNo(dicService.updateOrderNo());
				model.setCreateUser(getAgentName(request));
				if("Y".equals(model.getDealFlag())) {
					model.setDealUser(getAgentName(request));
					model.setDealTime(dateProvider.getDate());
				}
				callOrderService.save(model);
			}
			
			if("Y".equals(smsFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender("SYS");
				info.setReceiver(mobileNo);
				info.setSubject(null);
				info.setContent(smsContent);
				info.setChannel("MOBILE");
				info.setAddress(mobileNo);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(custId);
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			
			if("Y".equals(emailFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender(SystemConfiguration.getPropertyValue("mail.sender"));
				info.setReceiver(emailAdd);
				if(orderType==1) {
					info.setSubject("话务工单消息通知");
				} else if(orderType==2) {
					info.setSubject("结算工单消息通知");
				}
				info.setContent(emailContent);
				info.setChannel("EMAIL");
				info.setAddress(emailAdd);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(custId);
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			map.put(AJAX_MESSAGE, "true");
			map.put("custId", custId.toString());
			map.put("mobile", cust.getMobile());
			map.put("email", cust.getEmail());
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "话务工单保存异常");
		}
		return map;
	}
	
	@RequestMapping(value="/updateHistory", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> updateHistory(HttpServletRequest request, @RequestBody Map<String, Object> parmMap) {
		Map<String, String> map = new HashMap<String, String>(1);
		try {
			String orderId = (String) parmMap.get("orderId");
			if(StringUtils.isEmpty(orderId)) {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "工单ID为空");
				return map;
			}
			
			//处理工单信息
			CallOrder dbOrder = null;
		
			Long oldOrderId = null;
		
			if(StringUtils.isNotEmpty(orderId)) {
				oldOrderId = Long.parseLong(orderId);
			}
		
			if(oldOrderId!=null && oldOrderId>0) {
				dbOrder = callOrderService.get(oldOrderId);
			}
		
			if(dbOrder==null) {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "工单信息为空");
				return map;
			}
			
			dbOrder.setRemark((String) parmMap.get("remark"));
		
			if(StringUtils.isNotEmpty((String)parmMap.get("dealFlag"))) {
				dbOrder.setDealFlag((String) parmMap.get("dealFlag"));
			}
			
			if(Constant.IS_Y.equals(dbOrder.getDealFlag())) {
				dbOrder.setDealUser(getAgentName(request));
				dbOrder.setDealTime(dateProvider.getDate());
			}
			dbOrder.setUpdateUser(getAgentName(request));
			callOrderService.update(dbOrder);
			
			map.put(AJAX_MESSAGE, "true");
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "话务工单保存异常");
		}
		return map;
	}
	
	@RequestMapping(value = "/dealOrder", method=RequestMethod.POST)
	public String dealOrder(CallOrder order, HttpServletRequest request,
			HttpServletResponse response) {
		CallOrder dbOrder = null;
		CustomerInfo cust = null;
		try {
			if(order!=null) {
				if(order.getId()!=null && order.getId()>0) {
					dbOrder = callOrderService.get(order.getId());
					dbOrder.setDealRemark(order.getDealRemark());
					dbOrder.setStatus(order.getStatus());
					dbOrder.setDealUser(getAgentName(request));
					dbOrder.setUpdateUser(getAgentName(request));
					callOrderService.deal(dbOrder);
				} else {
					request.setAttribute("infoMsg", "工单ID为空");
					request.setAttribute("callJS", "history.back(-1);");
				}
				
				if(order.getCustId()!=null && order.getCustId()>0) {
					cust = customerInfoService.get(order.getCustId());
				}
			} else {
				request.setAttribute("infoMsg", "工单信息为空");
				request.setAttribute("callJS", "history.back(-1);");
			}
			
			request.setAttribute("order", dbOrder);
			request.setAttribute("cust", cust);
		} catch (ApplyException e) {
			e.printStackTrace();
			request.setAttribute("infoMsg", e.getMessage());
			request.setAttribute("callJS", "history.back(-1);");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("infoMsg", "结算工单处理异常");
			request.setAttribute("callJS", "history.back(-1);");
		}
		
		if(dbOrder !=null && dbOrder.getCustId()!=null && dbOrder.getCustId()>0) {
			cust = customerInfoService.get(dbOrder.getCustId());
		}
		
		// 保存工单信息
		request.setAttribute("order", dbOrder);
		
		request.setAttribute("cust", cust);

		return "infobird/call/dealResult";
	}
	
	@RequestMapping(value="/validate", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> validateAcctNo(@RequestBody CustomerInfo info) {
		Map<String, String> map = new HashMap<String, String>(1);
		
		
		try {
			//this.callOrderService.save(model);
			
			map.put(AJAX_MESSAGE, "true");
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "交易账号验证异常");
		}
		return map;
	}
	
	/**
	 * 根据交易账号获取客户信息
	 */
	@RequestMapping(value="/getCust", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> getCust(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>(1);
		//获取参数
		String acctNo = oConvertUtils.getString(request.getParameter("acctNo"));
		
		CustomerInfo cust = null;
		
		try {
			if(StringUtils.isNotEmpty(acctNo)) {
				cust = customerInfoService.getByAcctNo(acctNo);
				
				if(cust!=null) {
					map.put(AJAX_MESSAGE, "true");
					map.put("data", JSON.toJSONString(cust));
					map.put("data.custId", cust.getId().toString());
					map.put("data.mobile", cust.getMobile());
					map.put("data.email", cust.getEmail());
				} else {
					map.put(AJAX_MESSAGE, "false");
					map.put(ERR_MESSAGE, "该交易账号客户不存在");
				}
			} else {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "参数交易账号为空");
			}
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "获取客户信息异常");
		}
		return map;
	}
	
	@RequestMapping(value="/saveCustomer", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> saveCustomer(HttpServletRequest request, @RequestBody CustomerInfo info) {
		Map<String, String> map = new HashMap<String, String>(1);
		
		try {
			if(info!=null) {
				if(info.getId()!=null && info.getId()>0) {
					info.setUpdateUser(getAgentName(request));
					customerInfoService.update(info);
				} else {
					//校验手机号码与交易账号
					CustomerInfo dbCust = customerInfoService.getByMobile(info.getMobile());
					
					if(dbCust!=null && dbCust.getId()>0) {
						map.put(AJAX_MESSAGE, "false");
						map.put(ERR_MESSAGE, "该手机号码已存在");
					} else {
						CustomerInfo dbCust2 = customerInfoService.getByAcctNo(info.getAcctNo());
						if(dbCust2!=null && dbCust2.getId()>0) {
							map.put(AJAX_MESSAGE, "false");
							map.put(ERR_MESSAGE, "该交易账号已存在");
						} else {
							info.setCreateUser(getAgentName(request));
							customerInfoService.save(info);
							map.put(AJAX_MESSAGE, "true");
							map.put("custId", info.getId().toString());
							map.put("mobile", info.getMobile());
							map.put("email", info.getEmail());
						}		
					}
				}
			} else {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "联系人信息为空");
			}
			
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "联系人信息保存异常");
		}
		return map;
	}
	
	@RequestMapping(value="/getLocation", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> getLocation(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, String> map = new HashMap<String, String>(1);
		//获取呼入参数
		String phoneNo = oConvertUtils.getString(request.getParameter("phoneNo"));
		CustomerInfo cust = null;
		
		try {
		phoneNo = phoneNo.replaceAll("[（），、\\-\\(\\)\\,\\\\]",""); 
			
		//判断号码类型
		NumberUtil.Number num = NumberUtil.checkNumber(phoneNo);
		if(NumberUtil.PhoneType.CELLPHONE.equals(num.getType())) {
			//根据手机号码查询客户信息
			cust = customerInfoService.getByMobile(phoneNo);	
		} else if(NumberUtil.PhoneType.FIXEDPHONE.equals(num.getType())) {
			//根据固定号码查询客户信息
			cust = customerInfoService.getByPhoneNo(phoneNo);
		}
		
		if(cust==null) {
			cust = new CustomerInfo();
			if(NumberUtil.PhoneType.CELLPHONE.equals(num.getType())) {
				cust.setMobile(phoneNo);
				Location location = locationService.find(phoneNo);
				cust.setProvince(location.getProvince());
				cust.setCity(location.getCity());
				if(StringUtil.isNotEmpty(cust.getProvince())) {
					cust.setDependency(location.getProvince() + "-" + location.getCity());
				} else {
					cust.setProvince("其他");
					cust.setDependency("其他");
				}
			} else if(NumberUtil.PhoneType.FIXEDPHONE.equals(num.getType())) {
				cust.setTelephone(phoneNo);
				
				//根据区划查询归属地信息
				if(StringUtils.isNotEmpty(num.getCode())) {
					cust.setTelAbbr(num.getCode());
					Region region = regionService.getByAreaCode(num.getCode());
					if(region.getRegionType()==1) {
						//直辖市
						cust.setProvince(region.getShortName());
						cust.setCity(region.getShortName());
						cust.setDependency(region.getShortName() + "-" + region.getShortName());
					} else {
						//非直辖市
						cust.setProvince(region.getParentShortName());
						cust.setCity(region.getShortName());
						cust.setDependency(region.getParentShortName() + "-" + region.getShortName());
					}
				} else {
					cust.setProvince("其他");
					cust.setDependency("其他");
				}
			} else {
				//未知类型
				cust.setTelephone(phoneNo);
				cust.setProvince("其他");
				cust.setDependency("其他");
			}
		}
		
		
			map.put(AJAX_MESSAGE, "true");
			map.put("data", JSON.toJSONString(cust));
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "获取归属地信息异常");
		}
		return map;
	}
	
	@RequestMapping(value="/saveNotice", method=RequestMethod.POST)
	public @ResponseBody Map<String, String> saveNotice(HttpServletRequest request, @RequestBody Map<String, Object> parmMap) {
		Map<String, String> map = new HashMap<String, String>(1);
		CallOrder model = new CallOrder();
		Long orderId = null;
		Integer orderType = null;
		if(StringUtils.isNotEmpty((String)parmMap.get("orderId"))) {
			//工单不为空
			orderId = Long.parseLong((String)parmMap.get("orderId"));
			model = callOrderService.get(orderId);
			if(model!=null && model.getId()>0) {
				model.setId(orderId);
				orderType = model.getOrderType();
			} else {
				map.put(AJAX_MESSAGE, "false");
				map.put(ERR_MESSAGE, "工单信息异常");
				return map;
			}
		}
		String custId = (String) parmMap.get("custId");
		String smsFlag = (String) parmMap.get("smsFlag");
		String emailFlag = (String) parmMap.get("emailFlag");
		String mobileNo = (String) parmMap.get("mobileNo");
		String emailAdd = (String) parmMap.get("emailAdd");
		String smsContent = (String) parmMap.get("smsContent");
		String emailContent = (String) parmMap.get("emailContent");
		model.setSmsFlag2(smsFlag);
		model.setEmailFlag2(emailFlag);
		
		//消息推送记录
		NoticeInfo info = null;
		
		try {
			//更新工单信息
			model.setUpdateUser(getAgentName(request));
			callOrderService.update(model);
			
			if("Y".equals(smsFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender("SYS");
				info.setReceiver(mobileNo);
				info.setSubject(null);
				info.setContent(smsContent);
				info.setChannel("MOBILE");
				info.setAddress(mobileNo);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(Long.parseLong(custId));
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			
			if("Y".equals(emailFlag)) {
				info = new NoticeInfo();
				info.setOrderId(model.getId());
				info.setSender(SystemConfiguration.getPropertyValue("mail.sender"));
				info.setReceiver(emailAdd);
				if(orderType==1) {
					info.setSubject("话务工单消息通知");
				} else if(orderType==2) {
					info.setSubject("结算工单消息通知");
				}
				info.setContent(emailContent);
				info.setChannel("EMAIL");
				info.setAddress(emailAdd);
				info.setSendFlag(0);//未发送
				info.setSendState(0);//未处理
				info.setCustId(Long.parseLong(custId));
				info.setOperName(getAgentName(request));
				noticeInfoService.save(info);
			}
			
			map.put(AJAX_MESSAGE, "true");
		} catch (ApplyException e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			map.put(AJAX_MESSAGE, "false");
			map.put(ERR_MESSAGE, "通知信息保存异常");
		}
		return map;
	}
	
	/**
	 * 获取session中存储的坐席信息
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unused")
	private String getAgentName(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String agentName = (String)session.getAttribute("agentName");
		return agentName;
	}
}
